package com.example.demo.service.impl;

import com.example.demo.entity.Company;
import com.example.demo.entity.Storage;
import com.example.demo.mapper.CompanyMapper;
import com.example.demo.service.CompanyService;
import com.example.demo.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private StorageService storageService;

    @Override
    public Company createCompany(Company company) {
        // 设置默认值
        if (company.getCfreedays() == null) {
            company.setCfreedays(14); // 默认14天免费
        }
        if (company.getCrate() == null) {
            company.setCrate(0.5); // 默认费率0.5元/吨/天
        }
        company.setIsdeleted(0); // 默认未删除

        companyMapper.createCompany(company); // 执行插入
        return company; // 返回包含生成ID的对象
    }

    @Override
    public int deleteCompany(Integer cid) {
        // 删除前检查是否有关联仓库
        List<Storage> storages = storageService.findStoragesByCompanyId(cid);
        if (!storages.isEmpty()) {
            throw new RuntimeException("该公司有关联仓库，不能直接删除");
        }
        return companyMapper.deleteCompany(cid);
    }

    @Override
    public void logicalDeleteCompany(Integer cid) {
        // 逻辑删除公司及其仓库
        companyMapper.updateIsdeleted(cid);
        List<Storage> storages = storageService.findStoragesByCompanyId(cid);
        storages.forEach(storage -> storageService.logicalDeleteStorage(storage.getSid()));
    }

    @Override
    public int updateCompany(Company company) {
        return companyMapper.updateCompany(company);
    }

    @Override
    public Company findCompanyById(Integer cid) {
        return companyMapper.findCompanyById(cid);
    }

    @Override
    public List<Company> findAllValidCompanies() {
        return companyMapper.findAllCompanies();
    }

    @Override
    public List<Company> findCompaniesByPort(String portName) {
        return companyMapper.findAllCompanies().stream()
                .filter(c -> portName.equals(c.getCbelong()))
                .collect(Collectors.toList());
    }

    @Override
    public List<Company> findCompaniesByManager(String managerName) {
        return companyMapper.findAllCompanies().stream()
                .filter(c -> managerName.equals(c.getCmanager()))
                .collect(Collectors.toList());
    }
}